package com.guigu.eduservice.controller;

import com.github.pagehelper.PageInfo;
import com.guigu.common.utils.R;
import com.guigu.eduservice.entity.Role;
import com.guigu.eduservice.service.RoleService;
import com.guigu.eduservice.vo.ArticleVo;
import com.guigu.eduservice.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.List;

import static com.guigu.common.utils.R.ok;

/**
 * <p>
 * 角色表（用于RBAC权限控制） 前端控制器
 * </p>
 *
 * @author janecraft
 * @since 2025-09-27
 */
@RestController
@RequestMapping("/eduservice/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    //角色表的分页查询
    @PostMapping("/getRolePage/{PageNo}/{PageSize}")
    public R getRolePage(@RequestBody RoleVo vo,
                         @PathVariable("PageNo") Integer PageNo,
                         @PathVariable("PageSize") Integer PageSize){
        PageInfo<Role> rolePage = roleService.getRolePage(PageNo, PageSize, vo);
      return  R.ok().data("list",rolePage);
    }

    //删除角色表
    @DeleteMapping("/{id}")
    public R deleteRole(@PathVariable("id") Long RoleId){
        roleService.deleteRolePermissionsByRoleId(RoleId);

        boolean b = roleService.removeById(RoleId);
        if(b){
            return R.error().data("ok","删除成功");
        }
        return R.error().data("no","删除失败");
    }

    //添加角色
    @PostMapping()
    public R addRole(@RequestBody Role role) { // 自定义DTO接收前端参数
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());

        boolean result = roleService.addRoleWithPermissions(role, role.getGetPermissionIds());
       if(result){
          return R.ok().data("ok","添加成功");
       }
        return  R.error().data("no","添加失败");
    }


    //根据角色id查询
    @GetMapping("/{roleId}")
    public R getRole(@PathVariable("roleId") Long roleId) {
        Role role = roleService.getRoleWithPermissions(roleId);
        return R.ok().data("role",role);
    }

    //修改角色表
    @PutMapping
    public R updateRole(@RequestBody Role role) {
        boolean result = roleService.updateRoleWithPermissions(role);
        if(result){
            return R.ok().data("ok","修改成功");
        }
        return R.ok().data("ok","修改失败");
    }

    //查询所有角色
    @GetMapping("/getRoleAll")
    public R getRoleAll(){
        List<Role> list = roleService.list();
        return R.ok().data("list",list);
    }

}
